import { defineConfig } from "vite";
import uni from "@dcloudio/vite-plugin-uni";
import UnoCSS from 'unocss/vite';

const os = require('os'), fs = require("fs");

function getIPAdress() {
  const interfaces = os.networkInterfaces();
  for (let devName in interfaces) {
    const iface = interfaces[devName];
    for (let i = 0; i < iface.length; i++) {
      const alias = iface[i];
      if (alias.family === 'IPv4' && !alias.internal && /^192\.168\.+./.test(alias.address)) {
        return alias.address;
      }
    }
  }
  return "";
}

function getManifest(path: string) {
  const manifest = fs.readFileSync('./src/manifest.json', { encoding: 'utf-8' }),
    manifestArr = manifest.split(/\n/).map(str => str.replace(/(^\s*)|(\s*$)/g, "")),
    pathArr = path.split(".");
  for (let [index, i] = [0, 0]; index < manifestArr.length; index++) {
    const item = manifestArr[index];
    if (new RegExp(`^"${pathArr[i]}"`).test(item)) ++i;
    if (i === pathArr.length) {
      const value = item.slice(item.indexOf(':') + 1, item.length),
        result = value.slice(0, value.lastIndexOf(",") === -1 ? value.length : value.lastIndexOf(","));
      return result.replace(/(^\s*)|(\s*$)/g, "");
    }
  }
  return "";
}

// https://vitejs.dev/config/
export default defineConfig({
  define: {
    'process.env.DEV_URL': `"http://${getIPAdress()}:${getManifest("h5.devServer.proxy.port")}"`,
    'process.env.RELEASE_URL': getManifest("h5.devServer.proxy./api.target"),
    'process.env.ROUTE_PREFIX': getManifest("h5.router.base"),
  },
  plugins: [
    uni(),
    UnoCSS(),
  ],
});